<template>
  <div class="search">
    <label for="search_val" class="search__lab">
      <i class="iconfont icon-tubiaozhizuomoban1-06"></i>
    </label>
    <input type="text" id="search_val" class="search__inp" placeholder="搜索歌曲" v-model.trim="title">
    <span class="search__del" v-show="title" @click="delTitle">
      <i class="iconfont icon-delete"></i>
    </span>
  </div>
</template>
<script setup>
import { customRef, watch,defineEmits } from "vue";
import { useStore } from "vuex";

const store = useStore()
const emit = defineEmits(['change-title'])
// 搜索框数据
const title = useDebouncedRef('')
//清除搜索内容 
const delTitle = () =>{
  title.value=''
}

watch(title,
  ()=>{
    emit('change-title',title.value)
  }
)
watch(store.state,
  (val)=>{
    title.value = val.query
  }
)
// 防抖
function useDebouncedRef(value, delay = 500) {
  let timeout
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          value = newValue
          trigger()
        }, delay)
      },
    }
  })
}

</script>

<style lang="stylus" scoped>
.search
  margin-top 5px
  box-sizing border-box
  position relative
  padding 0 14px
  overflow hidden
  .search__lab
    position absolute
    left 20px
    top 5px
    color #ccc
    .iconfont
      font-size 20px
  .search__inp
    box-sizing border-box
    width 100%
    border-radius 15px
    height 35px
    padding-left 35px
    padding-right 35px
    outline none
    background #d8d8d840
    border none
  .search__del
    position absolute
    right 25px
    top 8px
    color #ccc
</style>